package com.itsm.service;

import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

//获取企业微信的应用token
@Service
public class AccessTokenService {
    private static final String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

    // 缓存access_token，避免频繁获取
    private static String accessToken;
    private static String wenToken;
    private static long expiredTime;
    private static long wenTokenTime;

    /**
     * 获取access_token
     * @param corpId 企业ID
     * @param secret 应用secret
     * @return access_token
     * @throws IOException
     */
    public String getAccessToken(String corpId, String secret) throws IOException {
        //如果缓存中的access_token还没有过期，则直接返回缓存中的access_token
        if (accessToken != null && System.currentTimeMillis() < expiredTime) {
            return accessToken;
        }
        // 向企业微信API请求access_token
        URL url = new URL(ACCESS_TOKEN_URL + "?corpid=" + corpId + "&corpsecret=" + secret);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        //解析返回结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuilder result = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        reader.close();
        conn.disconnect();

        //解析JSON格式的返回结果
        JSONObject json = new JSONObject(result.toString());
        if (json.getInt("errcode") == 0) {
            accessToken = json.getString("access_token");
            // access_token有效期为7200秒，这里设置提前60秒过期
            expiredTime = System.currentTimeMillis() + (7200 - 60) * 1000;
            return accessToken;
        } else {
            throw new IOException("Failed to get access_token, errcode: " + json.getInt("errcode") + ", errmsg: " + json.getString("errmsg"));
        }
    }

    public String getWenToken(String loginName, String password) throws IOException {
        //如果缓存中的access_token还没有过期，则直接返回缓存中的access_token
        if (wenToken != null && System.currentTimeMillis() < wenTokenTime) {
            return wenToken;
        }
        // 向企业微信API请求access_token
        URL url = new URL("https://www.0531yun.com/api/getToken" + "?loginName=" + loginName + "&password=" + password);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        //解析返回结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuilder result = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        reader.close();
        conn.disconnect();


        //解析JSON格式的返回结果
        JSONObject json = new JSONObject(result.toString());
        JSONObject to = json.getJSONObject("data");
        wenToken = to.getString("token");
        // access_token有效期为7200秒，这里设置提前60秒过期
        wenTokenTime = System.currentTimeMillis() + (7200 - 60) * 1000;
        return wenToken;

    }
}
